<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

$message = '';

try {
    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['email', 'password', 'username'] as $value) {

        // 判断是否有传入所需要的参数
        if (!isset($_POST[$value])) {
            throw new Exception(fieldMap($value).'为必传项');
        }

        // 判断参数是否为空
        if (empty($_POST[$value])) {
            throw new Exception(fieldMap($value).'不能为空');
        };

        if ($value === 'password' && strlen($_POST[$value]) < 6) {
            throw new Exception('密码长度不能小于6位');
        }

        if ($value === 'username' && strlen($_POST[$value]) < 2) {
            throw new Exception('用户名长度不能小于2位');
        }
    }

    // 判断注册的邮箱是否重复
    $sql = 'select * from users where email = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['email']]);
    if (!empty($stmt->fetch(PDO::FETCH_ASSOC))) {
        throw new Exception('该邮箱已注册过');
    };

    // 注册逻辑
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $sql = 'insert into users (username, email, password) values (?, ?, ?)';
    $stmt = $pdo->prepare($sql);
    $res = $stmt->execute([$username, $email, md5($password)]);

    myResponse('', 1, 200);
} catch (Exception $e) {
    $message = $e->getMessage();
    myResponse($message, 0, 200);
}


